package com.lap.context.starter.core.interceptor;

import com.lap.framework.common.constant.Header;
import com.lap.framework.common.tool.Uid;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

public class RequestIdInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(
      @NonNull HttpServletRequest request,
      @NonNull HttpServletResponse response,
      @NonNull Object handler) {
    String requestId = request.getHeader(Header.REQUEST_ID);
    MDC.put(Header.REQUEST_ID, StringUtils.defaultIfBlank(requestId, Uid.getStandardId()));
    return true;
  }

  @Override
  public void afterCompletion(
      @NonNull HttpServletRequest request,
      @NonNull HttpServletResponse response,
      @NonNull Object handler,
      Exception ex) {
    MDC.remove(Header.REQUEST_ID);
  }
}
